import Vue from 'vue';


const  state = {//定义了应用状态的数据结构，同样可以在这里设置默认的初始状态。
    cartList:[],

}

const actions = {//支持异步的操作，解决的异步的操作分发，
  addToCart(context,payload){
    context.commit("addToCart",payload)
  },
  decreaseCart(context,payload){
      context.commit("decreaseCart",payload)
  }
}

const mutations = { //调用 mutations 是唯一允许更新应用状态的地方,mutations对应的是commit。只支持同步，不支持异步
  addToCart(state,payload){
    var isChiose = false;
    for (var i = 0; i < state.cartList.length; i++) {
      if (state.cartList[i]._id==payload._id) {
          var index = i;
          isChiose = true;
          break;
      }
    }
    if (isChiose) {
        state.cartList.splice(index,0,payload)
    }else{
        state.cartList.push(payload)
    }
  },
  decreaseCart(state,payload){
      for (var i = 0; i < state.cartList.length; i++) {
          if (state.cartList[i]._id == payload._id) {
              state.cartList[i].count--;
              break;
          }
      }
  }

}
const getters = {//允许组件从 Store 中获取数据
  cartList(state){
    var cart = [];
    for (var i = 0; i < state.cartList.length; i++) {
        var haveIt = false;
        for (var j = 0; j < cart.length; j++) {
            if (state.cartList[i]._id == cart[j]._id) {
                haveIt = true;
                break;
            }
        }
        if (haveIt) {
            cart[j].count++;
        }else{
            var data = state.cartList[i];
            data.count=1;
            cart.push(data)
        }
    }
    return cart
  }

}


export default {
  state,
  actions,
  mutations,
  getters

}

